package com.student.liu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.student.liu.entity.ShopCar;
import com.student.liu.mapper.IShopCarMapper;
import com.student.liu.service.IShopCarService;
import lombok.Data;
import org.apache.ibatis.annotations.Select;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Map;

@Service
public class ShopCarServiceImpl extends ServiceImpl<IShopCarMapper, ShopCar> implements IShopCarService {

    @Resource
    IShopCarMapper shopCarMapper;

    @Override
    public void addShopCar(ShopCar shopCar) {
        //当前请求者
        Integer userId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        shopCar.setUserId(userId);
        save(shopCar);
    }

    @Override
    public void removeShopCar(Integer id) {
        removeById(id);
    }

    @Override
    public IPage<Map<String, Object>> shopCarPage(Integer pageIndex, Integer pageSize) {
        Integer userId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        Page page = new Page(pageIndex, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("shop_car.id","shop_car.goods_id","goods.name","goods.image","goods.price","shop_car.inventory");
        queryWrapper.last("JOIN goods on shop_car.goods_id = goods.id " +
                "WHERE shop_car.user_id = " + userId);
        return pageMaps(page,queryWrapper);
    }


    @Override
    public void setInventory(Integer shopCarId,Short inventory) {
        ShopCar shopCar=new ShopCar();
        shopCar.setInventory(inventory);
        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.apply("set inventory={n} where id = {n}",inventory,shopCarId);
        queryWrapper.eq("id",shopCarId);
        update(shopCar,queryWrapper);
    }
}
